package org.example.chatroom.demos.service;

import lombok.extern.slf4j.Slf4j;
import org.example.chatroom.demos.mapper.UserMapper;
import org.example.chatroom.demos.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpSession;

@Slf4j
@Service
public class UserService {

    @Autowired
    private UserMapper userMapper ;

    public Object longin(User user, HttpSession httpSession){
        if(user == null ||!StringUtils.hasLength(user.getUserName()) || ! StringUtils.hasLength(user.getPassword())){
            return new User() ;
        }
        User user1 = userMapper.queryPasswordByName(user.getUserName());
        if(user1 == null || !user.getPassword().equals(user1.getPassword())){
            log.info("用户名或密码错误");
             return new User() ;
        }
        user.setPassword("");
        httpSession.setAttribute("USER_KEY",user1);
        return user1 ;
    }

    public Object insertUser(User user) {
        if(user == null ||!StringUtils.hasLength(user.getUserName()) || ! StringUtils.hasLength(user.getPassword())){
            return new User() ;
        }
       try{
           Integer result = userMapper.insertUser(user) ;
       }catch(DuplicateKeyException e){
           log.info("注册失败");
           user = new User();
       }
       user.setPassword("");
       return user ;
    }

    public Object getUserInfo(HttpSession session) {
        User user = (User) session.getAttribute("USER_KEY");
        if(user == null || user.getId() < 1){
            return new User();
        }
        return user ;
    }
}
